<?php

namespace App\Http\Controllers\Admin;

use App\Http\Config\ErrorCode;
use App\Models\Admin\Configs;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Excel;

class ApplyController extends BaseController
{
    public function __construct(Request $request)
    {
        parent::__construct($request);
    }

	public function getPageList(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $pageNo = $request->post("pageNo", 1);
        $pageSize = $request->post("pageSize", 10);
        $searchKey = $request->post("search", '');
        $res = DB::table("apply_list")->select("id", "title as name", "create_time", "status")->where("mall_id", $request->mallData['id']);
        if($searchKey != ''){
            $res->where(function ($query) use ($searchKey) {
                $query->where('title', 'LIKE', '%' . $searchKey . '%');
            });
        }
        $data = array(
            'total' => $res->count(),
            'rows' => $res->skip(($pageNo-1) * $pageSize)->take($pageSize)->orderBy("create_time", "desc")->get()
        );
        $data['rows'] = json_decode(json_encode($data['rows']),true);
        foreach ($data['rows'] as &$item){
            $item["create_time"] = date("Y-m-d H:i:s", $item["create_time"]);
        }
        $data['rows'] = $this->transferFields($data['rows']);
        $this->returnData['data'] = $data;
        return $this->return_result($this->returnData);
    }

    public function create(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $title = trim($request->post('title',''));
        if(empty($title)){
            $this->returnData = ErrorCode::$admin_enum['params_error'];
            $this->returnData["msg"] = "标题不能为空";
            return $this->return_result($this->returnData);
        }
        $brief = trim($request->post('brief',''));
        if(empty($brief)){
            $this->returnData = ErrorCode::$admin_enum['params_error'];
            $this->returnData["msg"] = "申请内容详情不能为空";
            return $this->return_result($this->returnData);
        }
        $endLanguage = trim($request->post('endLanguage',''));
        if(empty($endLanguage)){
            $this->returnData = ErrorCode::$admin_enum['params_error'];
            $this->returnData["msg"] = "申请结束语不能为空";
            return $this->return_result($this->returnData);
        }
        $formId = trim($request->post('formId',''));
        if(empty($formId)){
            $this->returnData = ErrorCode::$admin_enum['params_error'];
            $this->returnData["msg"] = "申请表单不能为空";
            return $this->return_result($this->returnData);
        }
        $startTime = trim($request->post('startTime',''));
        $endTime = trim($request->post('endTime',''));
        if(empty($startTime) || empty($endTime)){
            $this->returnData = ErrorCode::$admin_enum['params_error'];
            $this->returnData["msg"] = "有效时间不能为空";
            return $this->return_result($this->returnData);
        }
        $status = $request->post('status', '');
        if($status == ''){
            $this->returnData = ErrorCode::$admin_enum['params_error'];
            $this->returnData["msg"] = "状态不能为空";
            return $this->return_result($this->returnData);
        }
        $res = DB::table('apply_list')->insert([
            "title" => $title, "brief" => $brief, "end_language" => $endLanguage, "form_id" => $formId,
            "start_time" => is_numeric($startTime) ? $startTime : strtotime($startTime), "end_time" => is_numeric($endTime) ? $endTime : strtotime($endTime),
            "day_count" => $request->post('dayCount', 1), "week_count" => $request->post('weekCount', 1),
            "month_count" => $request->post('monthCount', 1), "max_people_num" => $request->post('maxPeopleNum', 1),
            "each_people_num" => $request->post('eachPeopleNum', 1), "status" => $status, 'create_time' => time(),
            "mall_id" => $request->mallData['id']
        ]);
        if(!$res){
            $this->returnData = ErrorCode::$admin_enum['fail'];
            $this->returnData['msg'] = '添加失败';
            return $this->return_result($this->returnData);
        }
        $this->returnData['msg'] = '添加成功';
        return $this->return_result($this->returnData);
    }

    public function getInfo(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $res = DB::table('apply_list')->where("id", $request->id)->first();
        $res = json_decode(json_encode($res),true);
        if($res){
            $res["create_time"] = date("Y-m-d H:i:s", $res["create_time"]);
            $res["start_time"] = date("Y-m-d H:i:s", $res["start_time"]);
            $res["end_time"] = date("Y-m-d H:i:s", $res["end_time"]);
        }else{
            $res = [];
        }
        $this->returnData['data'] = $this->transferFields($res);
        return $this->return_result($this->returnData);
    }

    public function edit(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $id = $request->id;
        $title = trim($request->post('title',''));
        if(empty($title)){
            $this->returnData = ErrorCode::$admin_enum['params_error'];
            $this->returnData["msg"] = "标题不能为空";
            return $this->return_result($this->returnData);
        }
        $brief = trim($request->post('brief',''));
        if(empty($brief)){
            $this->returnData = ErrorCode::$admin_enum['params_error'];
            $this->returnData["msg"] = "申请内容详情不能为空";
            return $this->return_result($this->returnData);
        }
        $endLanguage = trim($request->post('endLanguage',''));
        if(empty($endLanguage)){
            $this->returnData = ErrorCode::$admin_enum['params_error'];
            $this->returnData["msg"] = "申请结束语不能为空";
            return $this->return_result($this->returnData);
        }
        $formId = trim($request->post('formId',''));
        if(empty($formId)){
            $this->returnData = ErrorCode::$admin_enum['params_error'];
            $this->returnData["msg"] = "申请表单不能为空";
            return $this->return_result($this->returnData);
        }
        $startTime = trim($request->post('startTime',''));
        $endTime = trim($request->post('endTime',''));
        if(empty($startTime) || empty($endTime)){
            $this->returnData = ErrorCode::$admin_enum['params_error'];
            $this->returnData["msg"] = "有效时间不能为空";
            return $this->return_result($this->returnData);
        }
        $status = $request->post('status', '');
        if($status == ''){
            $this->returnData = ErrorCode::$admin_enum['params_error'];
            $this->returnData["msg"] = "状态不能为空";
            return $this->return_result($this->returnData);
        }
        $res = DB::table('apply_list')->where("id", $id)->update([
            "title" => $title, "brief" => $brief, "end_language" => $endLanguage, "form_id" => $formId,
            "day_count" => $request->post('dayCount', 1), "week_count" => $request->post('weekCount', 1),
            "month_count" => $request->post('monthCount', 1), "max_people_num" => $request->post('maxPeopleNum', 1),
            "each_people_num" => $request->post('eachPeopleNum', 1), "status" => $status,
            "start_time" => is_numeric($startTime) ? $startTime : strtotime($startTime), "end_time" => is_numeric($endTime) ? $endTime : strtotime($endTime),
        ]);
        if(!$res){
            $this->returnData = ErrorCode::$admin_enum['fail'];
            $this->returnData['msg'] = '修改失败';
            return $this->return_result($this->returnData);
        }
        $this->returnData['msg'] = '修改成功';
        return $this->return_result($this->returnData);
    }

    public function delete(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $res = DB::table('apply_list')->where("id", $request->id)->delete();
        if(!$res){
            $this->returnData = ErrorCode::$admin_enum['fail'];
            $this->returnData['msg'] = '删除失败';
            return $this->return_result($this->returnData);
        }
        $this->returnData['msg'] = '删除成功';
        return $this->return_result($this->returnData);
    }

    public function getApplyRecordList(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        if(empty($request->id)){
            $this->returnData = ErrorCode::$admin_enum['fail'];
            $this->returnData['msg'] = '申请列表ID不能为空';
            return $this->return_result($this->returnData);
        }
        $pageNo = $request->post("pageNo", 1);
        $pageSize = $request->post("pageSize", 10);
        $searchKey = $request->post("search", '');
        $formData = DB::table("setting_form as sf")->select("sf.form_data")
            ->leftJoin('apply_list as al','al.form_id','=','sf.id')
            ->where("al.id", $request->id)->first();
        $formData = json_decode(json_encode($formData),true);
        $res = DB::table("apply_record as ar")->select("ar.id", "ar.form_data", "ar.create_time", "m.name")
            ->leftJoin('member as m','m.id','=','ar.user_id')
            ->where("list_id", $request->id);
        if($searchKey != ''){
            $res->where(function ($query) use ($searchKey) {
                $query->where('m.name', 'LIKE', '%' . $searchKey . '%');
            });
        }
        $data = array(
            'total' => $res->count(),
            'rows' => $res->skip(($pageNo-1) * $pageSize)->take($pageSize)->orderBy("create_time", "desc")->get(),
            "formData" => json_decode($formData["form_data"], true),
        );
        $data['rows'] = json_decode(json_encode($data['rows']),true);
        foreach ($data['rows'] as &$item){
            $item["create_time"] = date("Y-m-d H:i:s", $item["create_time"]);
            $item["form_data"] = json_decode($item["form_data"], true);
            foreach ($item["form_data"] as $key => $f){
                if(isset($f["reply"])){
                    if($f["type"] == "UploadPicture"){
                        if(is_array($f["reply"])){
                            foreach ($f["reply"] as &$tt){
                                $tt = $this->processingPictures($tt);
                            }
                        }else{
                            $f["reply"] = $this->processingPictures($f["reply"]);
                        }
                    }
                    $item["formItem{$key}"] = $f["reply"];
                }else{
                    $item["formItem{$key}"] = '';
                }
            }
            unset($item["form_data"]);
        }
        $data['rows'] = $this->transferFields($data['rows']);
        $this->returnData['data'] = $data;
        return $this->return_result($this->returnData);
    }

    // 导出
    public function punchCardRecordToExcel(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        if(empty($request->id)){
            $this->returnData = ErrorCode::$admin_enum['fail'];
            $this->returnData['msg'] = '申请列表ID不能为空';
            return $this->return_result($this->returnData);
        }
        $res = DB::table("apply_record")->select("form_data", "create_time")->where("list_id", $request->id);
        $data = $res->get();
        $data = json_decode(json_encode($data),true);
        if(count($data[0]) > 0) {
            foreach ($data as &$item){
                $item["form_data"] = json_decode($item["form_data"], true);
            }
            foreach ($data[0]["form_data"] as $k => $formData) {
                $arr[0][$k] = isset($formData["name"]) ? $formData["name"] : "未命名";
            }
            foreach ($data as $i => $item) {
                foreach ($item["form_data"] as $k => $v) {
                    if (isset($v["reply"])) {
                        if ($v["type"] == "UploadPicture") {
                            if (is_array($v["reply"])) {
                                foreach ($v["reply"] as &$tt) {
                                    $tt = $this->processingPictures($tt);
                                }
                            } else {
                                $v["reply"] = $this->processingPictures($v["reply"]);
                            }
                        }
                        $arr[$i+1][$k] = is_array($v["reply"]) ? implode(",", $v["reply"]) : $v["reply"];
                    } else {
                        $arr[$i+1][$k] = '';
                    }
                }
                $arr[$i+1][$k+1] = date("Y-m-d H:i:s", $item["create_time"]);
            }
            $arr[0][$k + 1] = "申请时间";
            $con = Configs::query()->where("mall_id", $request->mallData["id"])->first();
            if ($con->env == 'CLOUD') {
                $temp_file = tempnam(sys_get_temp_dir(), time() . ".xlsx");  //临时文件
                $a = Excel::create('申请列表', function ($excel) use ($arr) {
                    $excel->sheet('申请列表', function ($sheet) use ($arr) {
                        $sheet->rows($arr);
                    });
                })->string('xlsx');
                file_put_contents($temp_file, $a);
                $data['code'] = 3;
                $data['name'] = '申请列表.xlsx';
                $data['data'] = $temp_file;
                return $data;
            } else {
                Excel::create('申请列表', function ($excel) use ($arr) {
                    $excel->sheet('申请列表', function ($sheet) use ($arr) {
                        $sheet->rows($arr);
                    });
                })->export('xlsx');
            }
        }
    }

    public function transferFields($data){
        if(empty($data)){
            return [];
        }
        if(is_array($data)){
            $newData = [];
            foreach ($data as $k => $v){
                if(!is_numeric($k)){
                    $k = Str::camel($k);
                }
                if(is_array($v)){
                    $v = $this->transferFields($v);
                }
                if(is_null($v)){
                    $v = '';
                }
                $newData[$k] = $v;
            }
            return $newData;
        }else{
            if(is_null($data)){
                return [];
            }else {
                return Str::camel($data);
            }
        }
    }
}